import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/model/drama_list_entity.dart';
import 'package:flutter_taotaoshipin/model/drama_main_info_entity.dart';
import 'package:flutter_taotaoshipin/model/user_drama_auth_list_entity.dart';
import 'package:flutter_taotaoshipin/util/format_utils.dart';
import 'package:flutter_taotaoshipin/value/constant.dart';
import 'package:get/get.dart';

import '../../drama_detail/episode/drama_episode_state.dart';

class DramaEpisodeController extends GetxController
    with GetSingleTickerProviderStateMixin {
  DramaEpisodeController({
    this.mainInfoEntity,
    this.dramaListEntityList = const <DramaListEntity>[],
    this.userDramaAuthListEntityList =
        const <UserDramaAuthListEntity>[],
    this.isPlayingSort = 0,
  });

  final DramaEpisodeState state = DramaEpisodeState();

  // 主剧信息
  DramaMainInfoEntity? mainInfoEntity;
  // 分集列表
  List<DramaListEntity> dramaListEntityList;
  // 授权分集列表
  List<UserDramaAuthListEntity> userDramaAuthListEntityList;
  // 正在播放第集数
  int isPlayingSort;

  // 选集列表控制器
  ScrollController scrollController = ScrollController();

  @override
  void onInit() {
    super.onInit();

    if (dramaListEntityList.isNotEmpty) {
      if (Constant.isFree) {
        // 分集
        var anthologyList = _splitList(userDramaAuthListEntityList, 30);
        state.tabTitles = anthologyList.keys.toList();
      } else {
        // 分集
        var anthologyList = _splitList(dramaListEntityList, 30);
        state.tabTitles = anthologyList.keys.toList();
      }
      update();
    }

    scrollController.addListener(() {
      if (scrollController.offset <
          scrollController.position.maxScrollExtent) {
        double itemHeight = (Get.width - 15 * 2 - 10 * 5) / 6;
        double index = scrollController.offset / (itemHeight + 10) / 5;
        state.selectedTabIndex = index.round();
      } else {
        state.selectedTabIndex =
            state.tabTitles.length - 1;
      }
      update();
    });
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    scrollController.dispose();
    super.onClose();
  }

  Map<String, List<T>> _splitList<T>(List<T> list, int n) {
    var len = list.length;
    var out = <String, List<T>>{};
    for (var i = 0; i < len; i += n) {
      var key = '${i + 1}-${i + n > len ? len : i + 30}';
      out[key] = list.sublist(i, i + n > len ? len : i + n);
    }
    return out;
  }

  void xuanjiItemClicked(int index) {
    double itemHeight = (Get.width - 15 * 2 - 10 * 5) / 6;
    double offset = (itemHeight * 5 + 10 * 5) * index;
    // 不能滚出最大距离
    if (offset > scrollController.position.maxScrollExtent) {
      offset = scrollController.position.maxScrollExtent;
    }
    scrollController.animateTo(
      offset,
      duration: Duration(milliseconds: 500),
      curve: Curves.ease,
    );
  }
}
